﻿using NAudio.Wave;
using NAudio.Wave.SampleProviders;

using System.IO;

using Whisper.net;

namespace NAudio.WpfApp;

public class WhisperNet
{
    private WhisperProcessor processor;

    public WhisperNet()
    {
        Console.WriteLine("开始运行......");
        Console.WriteLine("加载模型中......");
        var directoryPath = Environment.CurrentDirectory;
        string modulePath = "C:\\Users\\Administrator\\Desktop\\AuthServer\\GlobalConfigurationConsole\\NAudio.WpfApp\\Module\\ggml-medium.bin";
        //string modulePath = "Module/ggml-medium.bin";
        string path = Path.Combine(directoryPath, modulePath);
        if (!File.Exists(path))
        {
            Console.WriteLine("模型文件不存在！");
            Console.ReadKey();
        }

        using var whisperFactory = WhisperFactory.FromPath(path);
        processor = whisperFactory.CreateBuilder().WithLanguage("auto").Build();
        Console.WriteLine("加载模型完成......");
    }

    public async Task<List<string>> StartAsync(string aviPath)
    {
        List<string> list = new();

        Console.WriteLine("开始加载音频文件......");
        string wavPath = aviPath;
        if (!File.Exists(wavPath))
        {
            Console.WriteLine("音频文件不存在！");
            Console.ReadKey();
        }
        Console.WriteLine("加载音频完成......");
        Console.WriteLine("语音识别中......");

        using var fileStream = File.OpenRead(wavPath);
        using var wavStream = new MemoryStream();

        //using var reader = new Mp3FileReader(fileStream);
        using var reader = new WaveFileReader(fileStream);

        var resampler = new WdlResamplingSampleProvider(reader.ToSampleProvider(), 16000);
        WaveFileWriter.WriteWavFileToStream(wavStream, resampler.ToWaveProvider16());

        wavStream.Seek(0, SeekOrigin.Begin);

        await foreach (var result in processor.ProcessAsync(wavStream))
        {
            list.Add($"{result.Start}->{result.End}: {result.Text}");
        }
        list.Add("语音识别完成!");

        return list;
    }
}